package com.aternity.monitors.update;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;

/**
 * @author Daniel Orr
 */
public class SyncFileContents {


    File srcDir;
    File targetDir;

    int counter = 0;

    public SyncFileContents(File srcDir, File targetDir) {
        this.srcDir = srcDir;
        this.targetDir = targetDir;
    }

    public void sync() throws IOException {
        syncImpl(srcDir, targetDir);
        System.out.println("Copied "+counter+" files");
    }

    public void syncImpl(File f1, File f2) throws IOException {
        if (!f1.isDirectory()) {
            if (f2.isDirectory()) {
                throw new IllegalStateException();
            }
            if (f1.getName().endsWith("Signature.xml") && f2.getName().endsWith("Signature.xml")) {
                System.out.println("\tcopy " + f1 + " to " + f2);
                FileUtils.copyFile(f1, f2);
                counter++;
            }
        } else {
            if (!f2.isDirectory()) {
                throw new IllegalStateException();
            }
            System.out.println("sync dirs: "+f1.getAbsolutePath()+"   and   "+f2.getAbsolutePath());
            final File[] f1Files = f1.listFiles();
            if (f1Files == null) {
                throw new IllegalStateException();
            }
            for (File f1File : f1Files) {
                final File match = findMatch(f1File, f2);
                if (match == null) {
                    System.out.println("\tNo match for: " + f1File.getAbsoluteFile());
                    return;
                }
                syncImpl(f1File, match);
            }
        }
    }

    private File findMatch(File f, File targetDir) {
        if(f.getName().contains("Signature.xml")){
            System.out.println();
        }
        String fname = StringUtils.remove(f.getName(), "+%28UX%29");
        fname = StringUtils.remove(fname, "%28UX%29");
        final File[] tFiles = targetDir.listFiles();
        if (tFiles == null) {
            throw new IllegalStateException();
        }
        for (File tFile : tFiles) {
            //final String baseName = FilenameUtils.getBaseName(tFile.getName());
            if (fname.startsWith(tFile.getName())) {
                return tFile;
            }
        }

        return null;
    }

    public static void main(String[] args) throws IOException {
        File src = new File("c:\\temp\\rois");
        File dest = new File("c:\\temp\\mm");
        SyncFileContents sfc = new SyncFileContents(src, dest);
        sfc.sync();
    }

}
